package com.dayuanit.dy15.ebook.bookshop.redis;

import com.dayuanit.dy15.ebook.bookshop.dto.CommodityHomeDTO;
import com.dayuanit.dy15.ebook.bookshop.dto.NavigationDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service("redisServiceTempleImpl")
public class RedisServiceTempleImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void zadd(String key, int score, String member) {
        redisTemplate.opsForZSet().add(key, member, score);
    }

    @Override
    public void zincrby(String key, int number, String member) {
        redisTemplate.opsForZSet().incrementScore(key, member, number);
    }

    @Override
    public void zrange(String key, int start, int stop) {

    }

    @Override
    public List<CommodityHomeDTO> zrevRange(String key, int start, int stop) {
        return null;
    }

    @Override
    public void addHomeBook(int number, String member) {
        String key = "ebook:home:books";
        redisTemplate.opsForZSet().incrementScore(key, member, number);
    }


    @Override
    public List<CommodityHomeDTO> zrevRange(int start, int stop) {
        String key = "ebook:home:books";

        Set<ZSetOperations.TypedTuple> set = redisTemplate.opsForZSet().rangeWithScores(key, start, stop);
        if (set.isEmpty()) {
            return Collections.emptyList();
        }

        List<CommodityHomeDTO> collect = set.stream().map(tuple -> {
            CommodityHomeDTO commodityHomeDTO = new CommodityHomeDTO();
            commodityHomeDTO.setCommoId(Long.parseLong(tuple.getValue().toString()));
            commodityHomeDTO.setScore(tuple.getScore());
            return commodityHomeDTO;
        }).collect(Collectors.toList());

        return collect;
    }


    @Override
    public void cacheNav(List<NavigationDTO> navs) {
        String key = "ebook:nav";
        redisTemplate.opsForValue().set(key, navs);
    }

    @Override
    public List<NavigationDTO> queryNav() {
        String key = "ebook:nav";
        List<NavigationDTO> o = (List<NavigationDTO>)redisTemplate.opsForValue().get(key);
        return o == null ? Collections.emptyList() : o;
    }
}
